$(function () {
    $("#jqGrid").jqGrid({
        url: '../shop/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '商铺名称', name: 'name', index: 'name', width: 80},
            {label: '商铺电话', name: 'phone', index: 'phone', width: 80, hidden: true},
            {
                label: '商铺图片', name: 'shopPic', index: 'shopPic', width: 80, formatter: function (value) {
                return transImg(value);
            }
            },
            {label: '介绍', name: 'introduce', index: 'introduce', width: 80},
            {label: '商铺地址', name: 'addressText', index: 'addressText', width: 80},

            ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.pageNum",
            total: "page.pages",
            records: "page.total"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
    $('#content').editable({
        inlineMode: false,
        alwaysBlank: true,
        height: 'auto', //高度
        language: "zh_cn",
        minHeight: '200px',
        spellcheck: false,
        plainPaste: true,
        enableScript: false,
        imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
        allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
        imageUploadURL: '../file/upload',//上传到本地服务器
        imageUploadParams: {id: "edit"},
        // imageManagerDeleteURL: '../sys/oss/delete',//删除图片(有问题)
        //imagesLoadURL: '../sys/oss/queryAll'//管理图片
    });
});


var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        shop: {},
        ruleValidate: {
            title: [
                {required: true, message: '活动主题不能为空', trigger: 'blur'}
            ]
        },
        q: {
            name: ''
        }
    },
    mounted: function () {
        //this.initMap();
    },
    methods: {
        /***************************************
         由于Chrome、IOS10等已不再支持非安全域的浏览器定位请求，为保证定位成功率和精度，请尽快升级您的站点到HTTPS。
         ***************************************/
        initMap:function (longitude,latitude) {
            var map, geolocation;

            map = new AMap.Map('container', {
                //center: [longitude, latitude],
                resizeEnable: true,
                //zoom: 10
            });
            AMap.plugin(['AMap.ToolBar', 'AMap.Scale','AMap.OverView', 'AMap.Geolocation',
                'AMap.Autocomplete','AMap.PlaceSearch'], function () {
                map.addControl(new AMap.ToolBar());
                map.addControl(new AMap.Scale());
                map.addControl(new AMap.OverView({isOpen:true}));

                /************************************************/
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    buttonPosition:'RB'
                });
                map.addControl(geolocation);
                geolocation.getCurrentPosition();
                AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
                AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息

                /*********************搜索框获取坐标***************************/
                var autoOptions = {
                        input: "tipinput"
                    };
                var auto = new AMap.Autocomplete(autoOptions);
                //构造地点查询类
                var placeSearch = new AMap.PlaceSearch({
                    map: map
                });
                AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
                function select(e) {
                    placeSearch.setCity(e.poi.adcode);
                    placeSearch.search(e.poi.name);  //关键字查询查询
                }

                /*********************鼠标点击获取坐标***************************/
                    //为地图注册click事件获取鼠标点击出的经纬度坐标
                var clickEventListener = map.on('click', function(e) {
                    document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
                });
            });
            //解析定位结果
            function onComplete(data) {
                var str=['定位成功'];
                str.push('经度：' + data.position.getLng());
                str.push('纬度：' + data.position.getLat());
                if(data.accuracy){
                    str.push('精度：' + data.accuracy + ' 米');
                }//如为IP精确定位结果则没有精度信息
                str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
                document.getElementById('tip').innerHTML = str.join('<br>');
            }
            //解析定位错误信息
            function onError(data) {
                document.getElementById('tip').innerHTML = '定位失败';
            }


        },

        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.shop = {avatar: '', itemPicUrl: '', scenePicUrl: ''};
            $('#content').editable('setHTML', '');
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id)

        },
        saveOrUpdate: function (event) {
            var url = vm.shop.id == null ? "../shop/save" : "../shop/update";

            //编辑器内容
            vm.shop.content = $('#content').editable('getHTML');
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.shop),
                success: function (r) {
                    if (r.status === "00000") {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../shop/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.status == "00000") {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get("../shop/info/" + id, function (r) {
                vm.shop = r.shop;
                vm.initMap(r.shop.longitude,vm.shop.latitude);
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        
        handleSuccessPicUrl: function (res, file) {
            vm.shop.picUrl = file.response.url;
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        
        eyeImagePicUrl: function () {
            var url = vm.shop.shopPic;
            eyeImage(url);
        },
       
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});

